<template>
	<view class="page" :style="{ 'min-height': h + 'px', 'padding-top': mt + 'px' }">
		<c-nav-bar :title="titleHeader"></c-nav-bar>
		<!-- 地图 -->
		<view class="v-map">
			<map id="myMap" :markers="markers" :polyline="polyline" style="width: 100%; height: 100%;" scale="12.6"
				:latitude="latitudeFrom" :longitude="longitudeFrom"></map>
		</view>
		<!-- 底部栏 -->
		<view class="bottom">
			<view class="head">
				{{ name }}
			</view>
			<view class="mid">
				<text>{{ busInfo.FirstStation }}</text>
				<image src="https://i.ringzle.com/file/20240122/8d1b3deb460e40e78a23d9761910db77.png" mode=""></image>
				<text>{{ busInfo.LastStation }}</text>
			</view>
			<view class="priceInfo">
				<image src="https://i.ringzle.com/file/20240124/9c4e5d751a8943408e31fb51542e2389.png" mode=""></image>
				<text>{{ busInfo.StartTimeStr }}</text>
				<image src="https://i.ringzle.com/file/20240124/f5761ba6db1748a793b9c3fb7031d94a.png" mode=""></image>
				<text class="night">{{ busInfo.EndTimeStr }}</text>
				<text>票价：{{ busInfo.Price / 100 }}元</text>

			</view>
		</view>
	</view>
</template>

<script>
import qqmap from '@/utils/map.js';

export default {
	data() {
		return {
			ringGo: '',
			ringTo: '',
			h: uni.getSystemInfoSync().windowHeight,
			mt: uni.getSystemInfoSync().statusBarHeight,
			titleHeader: '实时公交',
			busLineMapQuery: {
				Sheet: 2,
				LineId: ''
			},
			name: '',
			longitudeFrom: '',
			latitudeFrom: '',
			longitudeTo: '',
			latitudeTo: '',
			busInfo: {},
			polyline: [],
			newMarkers: [],
			markers: [
				{
					id: 1,
					latitude: '',
					longitude: '',
					width: 24,
					height: 40,
					iconPath: 'https://i.ringzle.com/file/20240125/e106579867d64d0b9c4e7c0783a431e6.png',
				},
				{
					id: 2,
					latitude: '',
					longitude: '',
					width: 24,
					height: 40,
					iconPath: 'https://i.ringzle.com/file/20240125/d8d1fb4e15594adf96eda4ff410426a3.png'
				}
			],
			mapCtx: null
		}
	},
	async onLoad({
		id,
		name,
		lastStation,
		firstStation,
		sheetId
	}) {
		this.ringGo = firstStation
		this.ringTo = lastStation
		this.busLineMapQuery.LineId = id
		this.busLineMapQuery.Sheet = sheetId
		this.name = name
		await this.getMap()

		const _this = this

		//调用距离计算接口
		qqmap.direction({
			mode: 'transit', //'transit'(公交路线规划)
			//from参数不填默认当前地址
			from: {
				latitude: _this.latitudeFrom,
				longitude: _this.longitudeFrom,
			},
			to: {
				latitude: _this.latitudeTo,
				longitude: _this.longitudeTo
			},
			success: function (res) {
				var ret = res.result.routes[0];
				var count = ret.steps.length;
				var pl = [];
				var coors = [];
				//获取各个步骤的polyline
				for (var i = 0; i < count; i++) {
					if (ret.steps[i].mode == 'WALKING' && ret.steps[i].polyline) {
						coors.push(ret.steps[i].polyline);
					}
					if (ret.steps[i].mode == 'TRANSIT' && ret.steps[i].lines[0].polyline) {
						coors.push(ret.steps[i].lines[0].polyline);
					}
				}
				//坐标解压（返回的点串坐标，通过前向差分进行压缩）
				var kr = 1000000;
				for (var i = 0; i < coors.length; i++) {
					for (var j = 2; j < coors[i].length; j++) {
						coors[i][j] = Number(coors[i][j - 2]) + Number(coors[i][j]) / kr;
					}
				}
				//定义新数组，将coors中的数组合并为一个数组

				var coorsArr = [];
				for (var i = 0; i < coors.length; i++) {
					coorsArr = coorsArr.concat(coors[i]);
				}
				//将解压后的坐标放入点串数组pl中
				for (var i = 0; i < coorsArr.length; i += 2) {
					pl.push({
						latitude: coorsArr[i],
						longitude: coorsArr[i + 1]
					})
				}
				//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
				_this.latitude = pl[0].latitude
				_this.longitude = pl[0].longitude

				_this.polyline = [{
					points: _this.newMarkers,
					color: '#5298FF',
					width: 4,
				},]
			},
			fail: function (error) {
				console.error(error);
			},
			complete: function (res) {
				console.log(res);
			}
		});


	},

	methods: {
		setMapCenter(latitude, longitude) {//点击回到自己当前位置的方法
			const mapCtx = uni.createMapContext("myMap", this);
			mapCtx.moveToLocation({
				latitude: latitude,
				longitude: longitude,
				success(res) {
					// console.log('调用成功', res)
				},
				fail(err) {
					console.log('调用失败')
				}
			})
		},
		getMiddleElement(arr) {
			if (arr.length > 3) {
				let middleIndex = Math.floor((arr.length - 1) / 2);
				return arr[middleIndex];
			} else {
				return arr[Math.floor(arr.length / 2)]
			}
		},
		// 初始化地图

		async getMap() {
			return new Promise((resolve, reject) => {
				if (this.ringGo === this.ringTo) {
					this.busLineMapQuery.Sheet = 3
				}
				this.$api.post('/api/apibusrealtime/getLineMap', this.busLineMapQuery).then(res => {
					// console.log(res)
					if (res.data.code === 0) {
						this.busInfo = res.data.data
						// 获取起点终点坐标
						this.longitudeFrom = res.data.data.LineTracks[0].Longitude + 0.01

						this.latitudeFrom = res.data.data.LineTracks[0].Latitude + 0.01
						this.longitudeTo = res.data.data.LineTracks[res.data.data.LineTracks
							.length - 1].Longitude
						this.latitudeTo = res.data.data.LineTracks[res.data.data.LineTracks
							.length - 1].Latitude

						// 赋值给markers

						this.newMarkers = res.data.data.LineTracks.map((item, index) => ({
							latitude: item.Latitude,
							longitude: item.Longitude,
						}))
						// 需要中心点坐标
						let adressAry = res.data.data.LineTracks
						let centerAdress = this.getMiddleElement(adressAry)
						this.setMapCenter(centerAdress.Latitude, centerAdress.Longitude)

						this.markers[0].latitude = res.data.data.LineTracks[0].Latitude //1经度
						this.markers[0].longitude = res.data.data.LineTracks[0].Longitude //1纬度
						this.markers[1].latitude = res.data.data.LineTracks[res.data.data
							.LineTracks.length - 1].Latitude //2经度
						this.markers[1].longitude = res.data.data.LineTracks[res.data.data
							.LineTracks.length - 1].Longitude //2纬度

						resolve();
					} else reject()
				})
			})
		},
	}
}
</script>

<style lang="scss">
.bottom {
	width: 750rpx;
	height: 301rpx;
	background-color: #fff;
	border-radius: 30rpx 30rpx 0 0;
	position: fixed;
	bottom: 0;
}

.head {
	margin-top: 30rpx;
	margin-left: 30rpx;
	font-size: 40rpx;
	font-weight: 700;

}

.mid {
	margin-top: 30rpx;
	margin-left: 10rpx;
	display: flex;

	text {
		font-size: 30rpx;
		font-weight: 700;
		margin-right: 20rpx;
		margin-left: 20rpx;
	}

	image {
		width: 24rpx;
		height: 8rpx;
		margin-top: 15rpx;
	}
}

.priceInfo {
	margin-top: 33rpx;
	margin-left: 4rpx;
	display: flex;

	image {
		width: 32rpx;
		height: 32rpx;
		margin-left: 26rpx;
		margin-right: 10rpx;
	}

	text {
		font-size: 24rpx;
		color: #222;
	}
}

.night {
	margin-right: 20rpx;
}

.v-map {
	width: 750rpx;
	height: 1720rpx;
}
</style>